<template>
  <div style="">
    <div class="top">
      <div class="top-name">
        <el-image style="width: 80px; height: 40px;margin-left:0px" class="fl" :src="require('@/assets/image/logo.png')" fit="fill"></el-image>
        <div class="top-title fl">岗位能力考核系统</div>
      </div>
      <div class="top-bottom">
          <div class="top-left">
              考试名称
          </div>
          <div class="top-right">
              <div class="time">
                  <div class="time-top">开始时间</div>
                  <div class="time-bottom">{{startTime?startTime.slice(11,16):'--:--'}}</div>
              </div>
              <div class="time">
                  <div class="time-top">结束时间</div>
                  <div class="time-bottom">{{endTime?endTime.slice(11,16):'--:--'}}</div>
              </div>
              <div class="type" v-if="time">{{time}}</div>
              <div class="type" v-else>已结束</div>
          </div>
      </div>
    </div>
    <div class="body">
        <div class="body-left">
            <div class="body-title">
                <span style="margin-left: 24px;">共{{form_num.all}}道题，满分100分。</span>
            </div>
            <div class="body-content" v-if="table.length">
                <div class="body-content-name">{{index+1}}.({{table[index].questionType.name}}){{table[index].titleDescription}}</div>
                <div style="width:100%" v-if="table[index].questionType.name=='单选题'">
                  <div class="body-select" v-for="(item, index1) in JSON.parse(table[index].questionOptions.options)" :key="index1">
                    <div class="select">
                      <el-image @click="getValue(index1, '' , '单选题')" style="width: 30px; height: 30px;margin-right:5px" class="fl" :src="require((answers[index].value+'').indexOf(zimu[index1])>-1?'@/assets/image/select.png':'@/assets/image/noSelect.png')" fit="fill"></el-image>
                      <div class="fl select-text" :style="getSelectColor(index1)"><span style="font-weight: bold;">{{item.name}}.</span>{{item.title}}</div>
                    </div>
                  </div>
                </div>
                <div style="width:100%" v-if="table[index].questionType.name=='多选题'">
                  <div class="body-select" v-for="(item, index1) in JSON.parse(table[index].questionOptions.options)" :key="index1">
                    <div class="select">
                      <el-image @click="getValue(index1, '' , '多选题')" style="width: 30px; height: 30px;margin-right:5px" class="fl" :src="require((answers[index].value+'').indexOf(zimu[index1])>-1?'@/assets/image/select.png':'@/assets/image/noSelect.png')" fit="fill"></el-image>
                      <div class="fl select-text" :style="getSelectColor(index1)"><span style="font-weight: bold;">{{item.name}}.</span>{{item.title}}</div>
                    </div>
                  </div>
                </div>
                <div style="width:100%" v-if="table[index].questionType.name=='案例题'">
                  <div class="body-fenge">
                    答题卡：
                  </div>
                  <el-input type="textarea" class="textarea" rows="6" placeholder="请输入" v-model="answers[index].value" @input="getValue('', '', '案例题')" />
                </div>
                <div style="width:100%" v-if="table[index].questionType.name=='情景题'">
                  <div class="body-fenge">
                    该题目需要在实操考场考试，请无视本题。
                  </div>
                </div>
            </div>
            <!-- <div class="body-content">
                <div class="body-content-name">{{index+1}}.题目是什么什么</div>
                <div class="body-content-name">案例：题目是什么什么</div>
            </div>
            <div class="body-fenge">
              答题卡：
            </div>
            <el-input type="textarea" class="textarea" rows="6" placeholder="请输入" /> -->

            <div class="body-bottom">
                <el-button v-if="index<table.length-1" @click="index++" size="smell" class="button1">下一题</el-button>
                <el-button v-if="index!=0" @click="index--" size="smell" class="button1">上一题</el-button>
                <el-button v-if="answers.length>0&&answers[index].biaoji" @click="answers[index].biaoji=!answers[index].biaoji;getYida()" size="smell" class="button1">取消标记</el-button>
                <el-button v-if="answers.length>0&&!answers[index].biaoji" @click="answers[index].biaoji=!answers[index].biaoji;getYida()" size="smell" class="button1">标记本题</el-button>
            </div>
        </div>
        <div class="body-right">
          <div class="body-right-body">
            <div class="tihaos">
              <div class="tihao shou" @click="index = index1" :style="getStyle(index1, item)" v-for="(item, index1) in table" :key="index1">
                {{index1+1}}
              </div>
            </div>
            <div class="tihao-types">
              <div class="tihao-type">
                <div class="tihao-type1">{{form_num.weida}}</div>
                <div class="tihao-type2">未答</div>
              </div>
              <div class="tihao-type">
                <div class="tihao-type1" style="border: 1px solid rgba(30, 144, 251, 1);">{{index + 1}}</div>
                <div class="tihao-type2">当前</div>
              </div>
              <div class="tihao-type">
                <div class="tihao-type1" style="background-color: rgba(227, 237, 255, 1);">{{form_num.yida}}</div>
                <div class="tihao-type2">已答</div>
              </div>
              <div class="tihao-type">
                <div class="tihao-type1" style="background-color: rgba(12, 192, 210, 1);color: rgba(255, 255, 255, 100);">{{form_num.biaoji}}</div>
                <div class="tihao-type2">标记</div>
              </div>
            </div>
          </div>
          <div class="jiaojuan shou" @click="dialog=true;callCamera()" v-if="form.video==1">提交试卷</div>
          <div class="jiaojuan shou" @click="dialog=true" v-else>提交试卷</div>
        </div>
    </div>
    <el-dialog title="提交试卷" width="50%" :visible.sync="dialog">
      <div class="dialog-body" v-if="form.video==1">
        <!--图片展示-->
        <video class="fl" ref="video" width="280" height="210" autoplay></video>
        <div slot="footer" class="dialog-footer" style="height:50px;line-height:50px">
          <el-button size="mini" @click="photograph()">拍照</el-button>
        </div>
        <!--canvas截取流-->
        <canvas v-show="!imgSrc" class="fl" ref="canvas" :width="width" :height="height"></canvas>
        <img v-show="imgSrc" :src="imgSrc" alt class="tx_img" />
      </div>
      <div v-else>
        <div v-if="flag">考试时间结束，请提交试卷，如果未提交，按0分处理！</div>
        <div v-else>点击提交试卷按钮提交数据并结束考试</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!flag" @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="toReady()" v-if="form.video==1">提交试卷</el-button>
        <el-button type="primary" @click="ready()" v-else>提交试卷</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import $http from '@/utils/request'
import $httpJSON from '@/utils/requestJSON'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data () {
    return {
      flag : false, // 判断倒计时状态
      time: '',
      startTime: '',
      endTime: '',
      value: '',
      width: 280,
      height: 210,
      imgSrc: '',
      index: 0,
      weida:[], // 储存未答题目的下标
      yida:[], // 储存已答题目的下标
      biaojis:[], // 储存标记题目的下标
      span1: 3,
      span2: 9,
      dialog: false,
      index_jibie: 0,
      value: '',
      values: [],
      table: [],
      zimu:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], // 字母数组
      // zimu:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], // 字母数组
      form_num:{
        all: 0,
        weida: 0,
        dangqian: 0,
        yida: 0,
        biaoji: 0
      },
      answers: [], // 储存答案列表,下标为x数据对应-下标为x的试题
      form: {},
      form_info: {
        account: '',
        createDatetime: '',
        id: '',
        idcard: '',
        logicalDelete: false,
        name: '',
        password: '',
        phone: '',
        portrait: '',
        professionId: '',
        sex: '',
        statusId: ''
      }
        
    }
  },
  mounted() {
    // localStorage.removeItem('answer')
    // console.log(JSON.parse(localStorage.getItem('shijuan')))
    this.form = JSON.parse(localStorage.getItem('shijuan'))
    this.form_info = JSON.parse(localStorage.getItem('info'))
    this.startTime = this.form.computerStartDatetime
    this.endTime = this.form.computerEndDatetime
    // this.endTime = '2020-11-18 20:00:00'
    $http.get('/examinee/exam/get/question/' + this.$route.query.id).then(response => {
        if (response.success) {
          response.data.forEach(item=> {
            this.answers.push({
              biaoji: false,
              id: item.id,
              value: '',
              values: [],
            })
          })
          this.table = response.data
          this.form_num.all = this.table.length
          // this.form_num.weida = response.data.length
          // this.form_num.yida = response.data.length
          
          if (localStorage.getItem('answer')) {
            this.answers = JSON.parse(localStorage.getItem('answer'))
            console.log('获取缓存答案', JSON.parse(localStorage.getItem('answer')))
          }
          this.getYida()
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
        
      }).catch(error => {
        console.log(error)
      })
    let time = setInterval(()=>{
      if(this.flag == true){
        clearInterval(time)
      }
      this.timeDown()
    },500)
  },
  watch:{
    'dialog' () {
      if (!this.dialog && this.flag) {
        this.dialog = true
      }
    }
  },
  methods: {
    timeDown () {
      const endTime = new Date(this.endTime)
      const nowTime = new Date();
      let leftTime = parseInt((endTime.getTime()-nowTime.getTime())/1000)
      let d = parseInt(leftTime/(24*60*60))
      let h = this.formate(parseInt(leftTime/(60*60)%24))
      let m = this.formate(parseInt(leftTime/60%60))
      let s = this.formate(parseInt(leftTime%60))
      if(leftTime <= 0){
        this.flag = true
        this.dialog=true
        if (this.form.video == 1) {
          this.callCamera()
        }
        return
      }
      m = d*24*60 + h*60 + m*1
      // this.time = `${d}天${h}小时${m}分${s}秒`
      this.time = `${m}:${s}`
    },
    formate (time) {
      if(time>=10){
        return time
      }else{
        return `0${time}`
      }
    },
    ready() {
      let query = {}
      for(let i = 0; i < this.answers.length; i++) {
        query[this.answers[i].id] = this.answers[i].value
      }
      query.examId = this.form.id
      query.examineeId = this.form_info.id
      query.paperId = this.form.paperId
      query.endImage = ''
      $httpJSON.post('/examinee/exam/submit/choice', query).then(response => {
        if (response.success) {
          this.dialog = false
          this.flag = false
          localStorage.setItem('answer', JSON.stringify(this.answers))
          this.$router.push({
              path:"/",//目标路径
              // query:{
              //     id: this.table[this.index_kaoshi].paperId,//要传的值
              // }
          })
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
        
      }).catch(error => {
        console.log(error)
      })
    },
    toReady() {
      let fileData = this.base64ToFile(this.imgSrc)
      let form = new FormData()
      // form.append('bizType', 9)
      let fileOfBlob = new File([fileData], new Date()+'.jpg')
      form.append('file',fileOfBlob)
      $http.post('/file/upload/begainimage', form).then(res => {
        if (res.success) {
          let query = {}
          for(let i = 0; i < this.answers.length; i++) {
            query[this.answers[i].id] = this.answers[i].value
          }
          query.examId = this.form.id
          query.examineeId = this.form_info.id
          query.paperId = this.form.paperId
          query.endImage = res.data
          $httpJSON.post('/examinee/exam/submit/choice', query).then(response => {
            if (response.success) {
              this.dialog = false
              this.closeCamera()
              localStorage.setItem('answer', JSON.stringify(this.answers))
              this.$router.push({
                  path:"/",//目标路径
                  // query:{
                  //     id: this.table[this.index_kaoshi].paperId,//要传的值
                  // }
              })
            } else  {
              this.$message({
                message: response.msg,
                type: 'error',
                duration: 2000
              })
            }
            
          }).catch(error => {
            console.log(error)
          })
        } else  {
          this.$message({
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
        
      }).catch(error => {
        console.log(error)
      })
    },
    getSelectColor(index) {
      if (this.answers[this.index].value + '' === index + '') {
        return 'color:#1E90FB'
      } else {
        return 'color:#333333'
      }
    },
    getSelectImage(index) {
      if (this.answers[this.index].value + '' === index + '') {
        return 'require(@/assets/image/select.png)'
      } else {
        return 'require(@/assets/image/noSelect.png)'
      }
    },
    getStyle(index, item) {
      let str = index%6==0?' margin-left:0px;':' margin-left:3px;'
      let str1 = ''
      if (this.answers[index].value + '' !== '') {
        str1 = ' background-color: rgba(227, 237, 255, 1);'
      }
      if (this.answers[index].biaoji) {
        str1 = ' color: rgba(255, 255, 255, 100); background-color: rgba(12, 192, 210, 1);'
      }
      if (index==this.index) {
        str1 = ' border: 1px solid rgba(30, 144, 251, 1);'
      }
      return str + str1
    },
    getValue(index, value, type) {
      let val = this.answers[this.index].value + ''
      if (type == '单选题') {
        val = this.zimu[index]
      }
      if (type == '多选题') {
        if (val.indexOf(this.zimu[index])>-1) {
          val = val.replace(','+this.zimu[index], '')
          val = val.replace(this.zimu[index], '')
        } else {
          if (val == '') {
            val = this.zimu[index]
          } else {
            val = val + ',' + this.zimu[index]
          }
        }
        let str = ''
        this.zimu.forEach(item=>{
          if (val.indexOf(item)>-1) {
            if (str === '') {
              str = item
            } else {
              str = str + ',' +item
            }
          }
        })
        val = str
      }
      if (type == '案例题') {
        this.getYida()
        this.$forceUpdate()
        return
      }
      console.log(val)
      this.answers[this.index] = {
        biaoji: false,
        id: this.table[this.index].id,
        value: val,
        values: [],
      }
      this.getYida()
      this.$forceUpdate()
    },
    getYida() {
      let k = 0
      let j = 0
      for (let i = 0; i < this.answers.length; i++) {
        if (this.answers[i].value + '' !== '' || this.answers[i].values.length > 0) {
          k++
        }
        if (this.answers[i].biaoji) {
          j++
        }
      }
      this.form_num.biaoji = j
      this.form_num.yida = k
      this.form_num.weida = this.answers.length - k
      localStorage.setItem('answer', JSON.stringify(this.answers))
    },
    // 调用摄像头
    callCamera () {
      // H5调用电脑摄像头API
      navigator.mediaDevices.getUserMedia({
        video: true
      }).then(success => {
        // 摄像头开启成功
        this.$refs['video'].srcObject = success
        // 实时拍照效果
        this.$refs['video'].play()
      }).catch(error => {
        console.error('摄像头开启失败，请检查摄像头是否可用！')
      })
    },
    //base64格式数据转换为file类型的文件
    base64ToFile(urlData, fileName) {
    let arr = urlData.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bytes = atob(arr[1]); // 解码base64
    let n = bytes.length
    let ia = new Uint8Array(n);
    while (n--) {
        ia[n] = bytes.charCodeAt(n);
    }
    return new File([ia], fileName||'image/jpeg', { type: mime });
},
    // 拍照
    photograph () {
      let ctx = this.$refs['canvas'].getContext('2d')
      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs['video'], 0, 0, this.width, this.height)
      // 转base64格式、图片格式转换、图片质量压缩
      let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)

      // var image = imgBase64.toDataURL("image/png");
      this.imgSrc = imgBase64;//赋值并预览图片
      
　　　 // 由字节转换为KB 判断大小
      let str = imgBase64.replace('data:image/jpeg;base64,', '')
      let strLength = str.length
      let fileLength = parseInt(strLength - (strLength / 8) * 2)
　　　 // 图片尺寸  用于判断
      let size = (fileLength / 1024).toFixed(2)
      console.log(size)

      // this.closeCamera()

 　　  // 上传拍照信息  调用接口上传图片 .........

      // 保存到本地
      // let ADOM = document.createElement('a')
      // ADOM.href = this.headImgSrc
      // ADOM.download = new Date().getTime() + '.jpeg'
      // ADOM.click()
    },
    // 关闭摄像头
    closeCamera () {
      if (!this.$refs['video'].srcObject) return
      let stream = this.$refs['video'].srcObject
      let tracks = stream.getTracks()
      tracks.forEach(track => {
        track.stop()
      })
      this.$refs['video'].srcObject = null
    }
  }
}
</script>

<style lang="scss" scoped>
.top-jibie{
  float: left;
  width: 60px;
  height: 46px;
  margin-right: 30px;
  color: rgba(153, 153, 153, 100);
  font-size: 14px;
  text-align: center;
  font-family: PingFangSC-Regular;
  display: flex;
  justify-content: center;
  align-items: center;
}
.top-select {
  color: #1890FF;
  border-bottom: 2px solid #1890FF;
}

.top-title{
    margin-top:16px;
    color: rgba(102, 102, 102, 100);
    font-size: 20px;
    font-family: MicrosoftYaHei;
    font-weight: bold;
    margin-left: 12px;
}
.top-bottom{
    width:100%;
    height: 68px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.top-left{
    color: rgba(58, 86, 135, 100);
    font-size: 30px;
    font-weight: bold;
    font-family: MicrosoftYaHei;
}
.top-right{
//   min-width: 400px;
  height: 68px;
  overflow: hidden;
  color: #1E90FB;
  font-size: 16px;
//   display: flex;
//   justify-content: center;
//   align-items: center;
}
.time{
    float: left;
    margin-left: 6px;
    width: 120px;
    height: 68px;
}
.type{
    float: left;
    margin-left: 8px;
    width: 158px;
    height: 68px;
    color: rgba(30, 144, 251, 100);
    font-size: 36px;
    font-weight: bold;
    font-family: MicrosoftYaHei;
    border-radius: 2px;
    background-color: rgba(227, 237, 255, 1);
    display: flex;
    justify-content: center;
    align-items: center;
}
.time-top{
    width:100%;
    height: 30px;
    color: rgba(255, 255, 255, 100);
    font-size: 14px;
    font-weight: bold;
    font-family: MicrosoftYaHei;
    background-color: #1E90FB;
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.time-bottom{
    width:100%;
    height: 38px;
    color: rgba(30, 144, 251, 100);
    font-size: 18px;
    font-weight: bold;
    font-family: MicrosoftYaHei;
    display: flex;
    justify-content: center;
    align-items: center;
}
.body{
    margin-top: 14px;
    margin-left: 20px;
    width:100%;
    height: calc(100vh - 118px - 14px - 40px);
}
.body-left{
    float:left;
    width: calc(100% - 340px);
    height: 100%;
    // background-color:white;
}
.body-right{
    float:right;
    width: 340px;
    height: 100%;
}
.body-right-body{
  width:100%;
  height:calc(100% - 45px - 20px);
}
.body-title{
    width: 100%;
    height:40px;
    background-color: rgba(30, 144, 251, 1);
    color: rgba(255, 255, 255, 100);
    font-size: 16px;
    font-family: MicrosoftYaHei;
    font-weight: bold;
    line-height: 40px;
}
.body-content{
  padding: 20px 20px 20px 20px;
  width: calc(100% - 0px);
  height:calc(100% - 105px - 20px);
  background-color:white;
}
.body-content1{
    padding: 20px 20px 20px 20px;
    width: calc(100% - 0px);
    max-height:calc(100% - 175px - 53px - 105px - 20px);
    background-color:white;
}
.body-bottom{
    width:100%;
    height:40px;
    margin-top:10px;
}
.button1{
    margin-left:20px;
    border-radius: 4px;
    float:left;
    // width: 136px;
    // height: 45px;
}
.body-content-name {
  margin-bottom: 10px;
  color: rgba(51, 51, 51, 100);
  font-size: 18px;
  font-family: MicrosoftYaHei;
}
.tihaos{
  width:280px;
  margin-left: 20px;
  margin-bottom: 40px;
  overflow: hidden;
  color: rgba(30, 144, 251, 100);
  font-size: 16px;
  font-family: MicrosoftYaHei;
  font-weight: bold;
  // background-color:pink;
}
.tihao{
  float: left;
  width:44px;
  height:44px;
  margin-bottom: 3px;
  background-color: white;
  border-radius: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.tihao-types{
  width:280px;
  margin-left: 20px;
  height:40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: rgba(30, 144, 251, 100);
  font-size: 16px;
  font-family: MicrosoftYaHei;
  font-weight: bold;
}
.tihao-type1{
  width:64px;
  height:40px;
  border-radius: 2px;
  background-color: rgba(255, 255, 255, 1);
  display: flex;
  justify-content: center;
  align-items: center;
}
.tihao-type2{
  width:64px;
  height:40px;

  display: flex;
  justify-content: center;
  align-items: center;
}

.kaoshi{
  width: 280px;
  height: 45px;
  margin-left: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgba(255, 255, 255, 100);
  font-size: 18px;
  font-weight:bold;
  background-image: linear-gradient(#0AD7AB, #0ABFD5);
  border-radius: 4px;
}
.jiaojuan{
  width: 280px;
  height: 45px;
  margin-left: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgba(255, 255, 255, 100);
  font-size: 18px;
  font-weight:bold;
  background-image: linear-gradient(#FF7C7C, #DD5353);
  border-radius: 4px;
}
.body-fenge{
  padding:20px 0 9px 0;
  width:100%;
  height:53px;
  // background-color: #F0F2F5;
  color: rgba(51, 51, 51, 100);
  font-size: 18px;
  font-weight:bold;
}
.el-textarea__inner{
  width:100%;
  // min-height: 175px!important;
}
.body-select{
  margin-top: 20px;
  widows: 100%;
  min-height:30px;
}
.select-text{
  line-height: 30px;
  color: rgba(51, 51, 51, 100);
  font-size: 18px;
  font-family: MicrosoftYaHei;
}
.dialog-body{
  overflow: hidden;
  margin: 0 auto;
  width: 600px;
  min-height:400px;
  display: flex;
  flex-direction:column;
  justify-content: center;
  align-items:center;
}
</style>
